package com.zhisuo.apicenter.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Charsets;
import com.zhisuo.apicenter.model.*;
import com.zhisuo.apicenter.service.ApiService;
import com.zhisuo.apicenter.service.ExpressManService;
import com.zhisuo.apicenter.service.UserManService;
import com.zhisuo.apicenter.util.SendSmsUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

/**
 * created by Intellij IDEA
 *
 * @author Chengzhifeng
 * @date 2020/10/12
 * @statement
 */
public class SyncCarStartDataJob {


    private UserManService userManService;
    @Autowired
    public void setUserManService(UserManService userManService) {
        this.userManService = userManService;
    }

    private ExpressManService expressManService;
    @Autowired
    public void setExpressManService(ExpressManService expressManService) {
        this.expressManService = expressManService;
    }

    private ApiService apiService;

    @Autowired
    public void setApiService(ApiService apiService) {
        this.apiService = apiService;
    }

    /**
     * 垃圾收取
     */
    public void syncRubbishDataTask() throws Exception {
        System.out.println("----------syncRubbishDataTask--------");

        //第一步，优先获取有几辆车
        List<String> listcarid=userManService.getListCarIdRubbishOrder();

        if(listcarid==null || listcarid.size()==0){
            return;
        }

        for(String carid:listcarid){

            List<RubbishOrder> listRubbishOrder=userManService.getListRubbishOrderBySync(carid);


            if(listRubbishOrder.size()>0 && listRubbishOrder!=null){

                ZhiSuoCar car=expressManService.getCarByCarId(Integer.parseInt(carid));
                String parkareaid=userManService.getParkAreaIdByCarId(car.getId());
                ParkArea pa=userManService.getParkAreaById(Integer.parseInt(parkareaid));



                String putjson="{\n";
                putjson=putjson+ " \"zone_id\": \""+pa.getStrcode()+"\",\n" +
                        " \"depot\": \""+car.getHomestation()+"\",\n" +
                        " \"depot_tw\": [0, 60],\n" + " \"stations\": {\n";
                for(RubbishOrder order:listRubbishOrder){
                    //根据地址
                    //ZhiSuoUserAddress address=userManService.getZhiSuoUserAddressById(order.getReceiptuseraddressid());
                    //ParkAreaBuild buildinfo=userManService.getParkAreaBuildById(address.getParkareabuildid());
                    //putjson=putjson+ " \"" +buildinfo.getCode()+ "\": [0, 60],";
                    putjson=putjson+ " \"" +order.getReceiptuseraddresscode()+ "\": [0, 60],";
                    expressManService.updateRubbishOrderByOrderId(order.getId());

                }
                putjson=putjson.substring(0,putjson.length()-1) +" },\n" +
                        " \"speed\": 10,\n" +
                        " \"wait\": 2 }";

                //System.out.println("----------syncDataTask--------putjson--------"+putjson);

                HttpClient client = HttpClientBuilder.create().build();
                HttpPost post=new HttpPost("http://49.235.73.243:80/tsptwrd");

                StringEntity stringEntity = new StringEntity(putjson);
                stringEntity.setContentType("application/json");
                post.setEntity(stringEntity);
                // 执行get请求，得到返回体
                HttpResponse response = client.execute(post);


                //System.out.println("data----"+response.getStatusLine().toString());
                // 判断是否正常返回
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    // 解析数据
                    String data = EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
                    //System.out.println("data----"+data);
                    if(StringUtils.isNotEmpty(data)){
                        JSONObject datajson=JSONObject.parseObject(data);
                        JSONArray jsonArray=datajson.getJSONArray("sequence");
                        if(jsonArray.size()>0){
                            //将以前的发车数据置为1
                            userManService.updateZhiSuoCarNextStopListStauts(carid);
                            String nextstop="";
                            for(int i=1;i<jsonArray.size();i++){
                                //存储
                                if(i==1){
                                    nextstop=jsonArray.get(i).toString();
                                }
                                //System.out.println("nextstop------"+jsonArray.get(i));
                                userManService.insertNewZhiSuoCarNextStopList(carid,jsonArray.get(i).toString());

                            }
                            //发送第一个车指令入库
                            ZhiSuoCar zhiSuoCar=userManService.getZhiSuoCarByCarId(carid);
//                          String stop_timeout_sec=apiService.getTcpUrlByTcpCenterUrl("opendoor_timeout_sec");
                            userManService.insertFirstNewZhiSuoCarNextStopTcp(zhiSuoCar.getSn(),zhiSuoCar.getId(),zhiSuoCar.getName(),nextstop,"",car.getHomestation());
                            System.out.println("submitCarStatus----syncDataTask---vin--"+zhiSuoCar.getSn()+"--nextstop----"+nextstop+"---"+new Date());
//                            //根据下一站指令，获取下一个用户
//                            List<DeliveryOrder> listNextStopDeliveryOrder=expressManService.getListNextDeliveryOrderByNextStop(nextstop,zhiSuoCar.getId()+"");
//
//                            if(listNextStopDeliveryOrder != null && listNextStopDeliveryOrder.size()>0){
//                                for(DeliveryOrder nextorder:listNextStopDeliveryOrder){
//                                    String[] params = new String[]{nextorder.getReceiptcode()};
//                                    String[] phoneNumbers =new String[]{nextorder.getReceiptusermobile()};
//                                    //发送短信
//                                    SendSmsUtil.sendSmsGetBox(params,phoneNumbers);
//                                    userManService.insertNewZhiSuoCarNextStopSms(nextorder.getReceiptcode(),nextorder.getReceiptusermobile(),nextorder.getCarid()+"",0);
//                                    //语音短信
//                                    userManService.insertNewZhiSuoCarNextStopSms("5,"+nextorder.getReceiptcode(),nextorder.getReceiptusermobile(),nextorder.getCarid()+"",5);
//
//                                }
//                            }


                        }


                    }

                }

            }



        }






    }



    /**
     * 收取快递发车
     */
    public void syncGetMailDataTask() throws Exception {
        System.out.println("----------syncGetMailDataTask--------");



        //第一步，优先获取有几辆车
        List<String> listcarid=userManService.getListCarIdSendOrder();

        if(listcarid==null || listcarid.size()==0){
            return;
        }

        for(String carid:listcarid){

            List<SendOrder> listSendOrder=userManService.getListSendOrderBySync(carid);


            if(listSendOrder.size()>0 && listSendOrder!=null){

                ZhiSuoCar car=expressManService.getCarByCarId(Integer.parseInt(carid));
                String parkareaid=userManService.getParkAreaIdByCarId(car.getId());
                ParkArea pa=userManService.getParkAreaById(Integer.parseInt(parkareaid));



                String putjson="{\n";
                putjson=putjson+ " \"zone_id\": \""+pa.getStrcode()+"\",\n" +
                        " \"depot\": \""+car.getHomestation()+"\",\n" +
                        " \"depot_tw\": [0, 60],\n" + " \"stations\": {\n";
                for(SendOrder order:listSendOrder){
                    //根据地址
                    //ZhiSuoUserAddress address=userManService.getZhiSuoUserAddressById(order.getSenduseraddressid());
                    ParkAreaBuild buildinfo=userManService.getParkAreaBuildById(order.getSenduseraddressid());
                    putjson=putjson+ " \"" +buildinfo.getCode()+ "\": [0, 60],";

                }
                putjson=putjson.substring(0,putjson.length()-1) +" },\n" +
                        " \"speed\": 10,\n" +
                        " \"wait\": 2 }";

                //System.out.println("----------syncDataTask--------putjson--------"+putjson);

                HttpClient client = HttpClientBuilder.create().build();
                HttpPost post=new HttpPost("http://49.235.73.243:80/tsptwrd");

                StringEntity stringEntity = new StringEntity(putjson);
                stringEntity.setContentType("application/json");
                post.setEntity(stringEntity);
                // 执行get请求，得到返回体
                HttpResponse response = client.execute(post);


                //System.out.println("data----"+response.getStatusLine().toString());
                // 判断是否正常返回
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    // 解析数据
                    String data = EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
                    //System.out.println("data----"+data);
                    if(StringUtils.isNotEmpty(data)){
                        JSONObject datajson=JSONObject.parseObject(data);
                        JSONArray jsonArray=datajson.getJSONArray("sequence");
                        if(jsonArray.size()>0){
                            //将以前的发车数据置为1
                            userManService.updateZhiSuoCarNextStopListStauts(carid);
                            String nextstop="";
                            for(int i=1;i<jsonArray.size();i++){
                                //存储
                                if(i==1){
                                    nextstop=jsonArray.get(i).toString();
                                }

                                //System.out.println("nextstop------"+jsonArray.get(i));
                                userManService.insertNewZhiSuoCarNextStopList(carid,jsonArray.get(i).toString());

                            }
                            //发送第一个车指令入库
                            ZhiSuoCar zhiSuoCar=userManService.getZhiSuoCarByCarId(carid);
//                            String stop_timeout_sec=apiService.getTcpUrlByTcpCenterUrl("opendoor_timeout_sec");
                            userManService.insertFirstNewZhiSuoCarNextStopTcp(zhiSuoCar.getSn(),zhiSuoCar.getId(),zhiSuoCar.getName(),nextstop,"",car.getHomestation());

                            //根据下一站指令，获取下一个用户
                            List<SendOrder> listNextStopDeliveryOrder=expressManService.getListNextSendOrderByNextStop(nextstop,zhiSuoCar.getId()+"");


                            if(listNextStopDeliveryOrder != null && listNextStopDeliveryOrder.size()>0){
                                for(SendOrder nextorder:listNextStopDeliveryOrder){
                                    String[] params = new String[]{nextorder.getSendcode()};
                                    String[] phoneNumbers =new String[]{nextorder.getSendmobile()};
                                    //发送短信
                                    SendSmsUtil.sendSmsGetBox(params,phoneNumbers);
                                    userManService.insertNewZhiSuoCarNextStopSms(nextorder.getSendcode(),nextorder.getSendmobile(),nextorder.getCarid()+"",0);
                                    //订单状态置为1
                                    userManService.updateSendOrderStatusByOrderId(nextorder.getId());
                                }
                            }


                        }


                    }

                }

            }



        }






    }







    /**
     * 派送快递发车
     * @throws Exception
     *
     * {
     *  "zone_id": "ydzd",
     *  "depot": "P8",
     *  "depot_tw": [60, 120],
     *  "stations": {
     *  "P9": [60, 120],
     *  "P10": [60, 120],
     *  "P11": [60, 180]
     *  },
     *  "speed": 20,
     *  "wait": 2 }
     */
    public void syncDataTask() throws Exception {
        System.out.println("----------syncDataTask--------");



        //第一步，优先获取有几辆车
        List<String> listcarid=userManService.getListCarIdDeliveryOrder();

        if(listcarid==null || listcarid.size()==0){
            return;
        }

        for(String carid:listcarid){

            List<DeliveryOrder> listDeliveryOrder=userManService.getListDeliveryOrderBySync(carid);


            if(listDeliveryOrder.size()>0 && listDeliveryOrder!=null){

                ZhiSuoCar car=expressManService.getCarByCarId(Integer.parseInt(carid));
                String parkareaid=userManService.getParkAreaIdByCarId(car.getId());
                ParkArea pa=userManService.getParkAreaById(Integer.parseInt(parkareaid));



                String putjson="{\n";
                putjson=putjson+ " \"zone_id\": \""+pa.getStrcode()+"\",\n" +
                        " \"depot\": \""+car.getHomestation()+"\",\n" +
                        " \"depot_tw\": [0, 60],\n" + " \"stations\": {\n";
                for(DeliveryOrder order:listDeliveryOrder){
                    //根据地址
                    //ZhiSuoUserAddress address=userManService.getZhiSuoUserAddressById(order.getReceiptuseraddressid());
                    //ParkAreaBuild buildinfo=userManService.getParkAreaBuildById(address.getParkareabuildid());
                    //putjson=putjson+ " \"" +buildinfo.getCode()+ "\": [0, 60],";
                    putjson=putjson+ " \"" +order.getReceiptuseraddresscode()+ "\": [0, 60],";

                }
                putjson=putjson.substring(0,putjson.length()-1) +" },\n" +
                        " \"speed\": 10,\n" +
                        " \"wait\": 2 }";

                //System.out.println("----------syncDataTask--------putjson--------"+putjson);

                HttpClient client = HttpClientBuilder.create().build();
                HttpPost post=new HttpPost("http://49.235.73.243:80/tsptwrd");

                StringEntity stringEntity = new StringEntity(putjson);
                stringEntity.setContentType("application/json");
                post.setEntity(stringEntity);
                // 执行get请求，得到返回体
                HttpResponse response = client.execute(post);


                //System.out.println("data----"+response.getStatusLine().toString());
                // 判断是否正常返回
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    // 解析数据
                    String data = EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
                    //System.out.println("data----"+data);
                    if(StringUtils.isNotEmpty(data)){
                        JSONObject datajson=JSONObject.parseObject(data);
                        JSONArray jsonArray=datajson.getJSONArray("sequence");
                        if(jsonArray.size()>0){
                            //将以前的发车数据置为1
                            userManService.updateZhiSuoCarNextStopListStauts(carid);
                            String nextstop="";
                            for(int i=1;i<jsonArray.size();i++){
                                //存储
                                if(i==1){
                                    nextstop=jsonArray.get(i).toString();
                                }
                                //System.out.println("nextstop------"+jsonArray.get(i));
                                userManService.insertNewZhiSuoCarNextStopList(carid,jsonArray.get(i).toString());

                            }
                            //发送第一个车指令入库
                            ZhiSuoCar zhiSuoCar=userManService.getZhiSuoCarByCarId(carid);
//                          String stop_timeout_sec=apiService.getTcpUrlByTcpCenterUrl("opendoor_timeout_sec");
                            userManService.insertFirstNewZhiSuoCarNextStopTcp(zhiSuoCar.getSn(),zhiSuoCar.getId(),zhiSuoCar.getName(),nextstop,"",car.getHomestation());
                            System.out.println("submitCarStatus----syncDataTask---vin--"+zhiSuoCar.getSn()+"--nextstop----"+nextstop+"---"+new Date());
                            //根据下一站指令，获取下一个用户
                            List<DeliveryOrder> listNextStopDeliveryOrder=expressManService.getListNextDeliveryOrderByNextStop(nextstop,zhiSuoCar.getId()+"");

                            if(listNextStopDeliveryOrder != null && listNextStopDeliveryOrder.size()>0){
                                for(DeliveryOrder nextorder:listNextStopDeliveryOrder){
                                    String[] params = new String[]{nextorder.getReceiptcode()};
                                    String[] phoneNumbers =new String[]{nextorder.getReceiptusermobile()};
                                    //发送短信
                                    SendSmsUtil.sendSmsGetBox(params,phoneNumbers);
                                    userManService.insertNewZhiSuoCarNextStopSms(nextorder.getReceiptcode(),nextorder.getReceiptusermobile(),nextorder.getCarid()+"",0);
                                    //语音短信
                                    userManService.insertNewZhiSuoCarNextStopSms("5,"+nextorder.getReceiptcode(),nextorder.getReceiptusermobile(),nextorder.getCarid()+"",5);

                                }
                            }


                        }


                    }

                }

            }



        }






    }


    public static void main(String args[]) throws Exception{
        String putjson="{\n" +
                " \"zone_id\": \"ydzd\",\n" +
                " \"depot\": \"P8\",\n" +
                " \"depot_tw\": [0, 60],\n" +
                " \"stations\": {\n" +
                " \"P9\": [0, 60],\n" +
                " \"P10\": [0, 60],\n" +
                " \"P11\": [0, 60]\n" +
                " },\n" +
                " \"speed\": 20,\n" +
                " \"wait\": 2 }";
//        HttpClient client = HttpClientBuilder.create().build();
//        HttpPost post=new HttpPost("http://49.235.73.243:80/tsptwrd");
        //System.out.println(putjson);
//        StringEntity stringEntity = new StringEntity(putjson);
//        stringEntity.setContentType("application/json");
//        post.setEntity(stringEntity);
//         // 执行get请求，得到返回体
//        HttpResponse response = client.execute(post);
//
//
//        System.out.println("data----"+response.getStatusLine().toString());
//        // 判断是否正常返回
//        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//            // 解析数据
//            String data = EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
//            System.out.println("data----"+data);
//            if(StringUtils.isNotEmpty(data)){
//                JSONObject datajson=JSONObject.parseObject(data);
//                JSONArray jsonArray=datajson.getJSONArray("sequence");
//                for(int i=0;i<jsonArray.size();i++){
//                    //存储
//                    System.out.println(jsonArray.get(i));
//                }
//
//            }
//
//        }
        SyncCarStartDataJob s=new SyncCarStartDataJob();
        s.syncDataTask();
//        Map<String,String> map=new HashMap<String,String>();
//        map.put("0","60"); //添加
//        System.out.println(map);


    }

}
